package cn.lee.test.service;

import cn.lee.test.common.base.repository.MyBaseJpaRepository;
import cn.lee.test.common.base.service.MyBaseJpaService;
import cn.lee.test.model.User;
import cn.lee.test.repository.UserRepository;
import cn.lee.test.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : lichl(李承霖)
 * create: 2022/2/23 23:24 周三
 */

@Service
public class UserService extends MyBaseJpaService<User, Long>{
  
  @Autowired
  private UserRepository repository;
  
  @Autowired
  private HttpServletRequest request;
  
  @Override
  protected MyBaseJpaRepository<User, Long> getRepository(){
    return repository;
  }
  
  // 判断用户和密码是否正确
  public User checkLogin(String username, String password){
    return repository.findByUserNameAndPasswordAndStatus(username, password, "active");
  }
  
  // 获取当前登录的用户信息
  @SneakyThrows
  public User getLoginUser(){
    
    // 解析当前登录者的JWT字符串中的载荷
    String JwtToken = request.getHeader("Authorization");
    if(StringUtils.isEmpty(JwtToken)){
      throw new Exception("请求头没有捕获JwtToken!");
    }
    try{
      // 校验JWT字符串
      Jws<Claims> decodedJWT = JwtUtils.decode(JwtToken);
      // 提取UserId查询用户对象
      String userId  = String.valueOf(decodedJWT.getBody().get("id"));
      
      return repository.findByIdAndStatus(Long.parseLong(userId),"Active");
    }catch(Exception e){
      throw  new Exception("jwt字符校验失败");
    }
  }
}
